import todoist, re, time

class TodoistAPI():

    def __init__(self, hass, token):
        self.hass = hass
        self.api = todoist.TodoistAPI(token)

    def init_project(self):
        api = self.api
        api.sync()
        project_name = '家庭助理'
        # 获取全部项目名称
        projects = []
        for project in api.state['projects']:
            name = project['name']
            if name == project_name:
                self.project = project
                return
            projects.append(name)
        if project_name not in projects:
            self.project = api.projects.add(project_name)
            api.commit()
            print('初始成功')

    def get_items(self, content=''):
        api = self.api
        project_data = api.projects.get_data(self.project['id'])
        try:
            items = project_data['items']
            if content != '':
                return list(filter(lambda item: item['content'] == content, items))
            return items
        except Exception as ex:
            print(ex)
        return []

    def parse_date(self, text):
        # 全中文解析
        matchObj = re.match(r'([^一二三四五六七八九十]+)?([一二三四五六七八九十]+)点(([一二三四五六七八九十]+)分)?(([一二三四五六七八九十]+)秒)?', text)
        if matchObj is not None:
            day = matchObj.group(1)
            h = matchObj.group(2)
            m = matchObj.group(4)
            s = matchObj.group(6)
            minute = 0
            if h is not None:
                hour = format_number(h)
                text = text.replace(h, str(hour))
            if m is not None:
                minute = format_number(m)
                text = text.replace(m, str(minute))
            if s is not None:
                text = text.replace(s, str(format_number(s)))
            # 没有指定日期，则默认当天
            if day is None:
                day = '今天'
                dt = time.localtime(time.time())
                # 如果提醒时间已过，则判定为下午或晚上
                if dt.tm_hour > hour and dt.tm_min > minute:
                    day = '下午' if hour < 6 else '晚上'
                text = f'{day}{text}'
        return text

    def add_item(self, content, due_date):
        api = self.api
        due_date = self.parse_date(due_date)
        print(content, due_date)
        items = self.get_items(content)
        # 定义时间
        _due = {
            'string': due_date
        }
        if len(items) > 0:
            item = items[0]
            api.items.update_date_complete(item['id'], due=_due)
        else:
            item = api.items.add(content, project_id=self.project['id'])        
            item.update(due=_due)
        api.commit()

    def delete_item(self, content):
        items = self.get_items(content)
        if len(items) > 0:
            item = items[0]
            item_id = item['id']
            api = self.api
            api.items.delete(item_id)
            api.commit()
            return item_id

########################################## 汉字转数字
common_used_numerals_tmp ={'零':0, '一':1, '二':2, '两':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '十':10, '百':100, '千':1000, '万':10000, '亿':100000000}
common_used_numerals = {}
for key in common_used_numerals_tmp:
  common_used_numerals[key.encode('cp936').decode('cp936')] = common_used_numerals_tmp[key]

def chinese2digits(uchars_chinese):
    try:
        uchars_chinese = uchars_chinese.encode('cp936').decode('cp936')
        total = 0
        r = 1              #表示单位：个十百千...
        for i in range(len(uchars_chinese) - 1, -1, -1):
            val = common_used_numerals.get(uchars_chinese[i])
            if val >= 10 and i == 0:  #应对 十三 十四 十*之类
                if val > r:
                    r = val
                    total = total + val
                else:
                    r = r * val
                #total =total + r * x
            elif val >= 10:
                if val > r:
                    r = val
                else:
                    r = r * val
            else:
                total = total + r * val
        return total
    except Exception as ex:
        return None

# 判断是否数字
def is_number(s):
    result = re.match(r'\d+', s)
    if result:
        return True
    else:
        return False

def format_number(num):
    if is_number(num) == False:
        num = chinese2digits(num)
    return int(num)